package com.yuanheng100.chinaregion;


import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.Modifier;
import javassist.NotFoundException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by hepeng on 2016/11/4.
 * Description : 更新 com.yuanheng100.chinaregion.consts.Region 代码工具类
 */
public class Parser {

    private static Parser parser = new Parser();

    private Parser(){

    }

    public static Parser getInstance(){
        return parser;
    }

    /**
     * 传入指定的 url 地址比如：http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201608/t20160809_1386477.html
     * 解析返回的html代码，得到地区码和地区名称数据，并以java代码的形式写入到指定的.java文件中,写入成功后格式化一下
     * java文件,方便下次进行同样封操作
     * @param url
     * @param filePath
     */
    public static void parse(String url,String filePath){

        BufferedReader bufr = null;
        BufferedWriter writer = null;
        try {
            LinkedHashMap<Integer,String> linkedMap = new LinkedHashMap<Integer, String>();

            // http请求，解析html
            Document document = Jsoup.connect(url).get();
            Elements spans = document.getElementsByTag("span");
            for(int i = 0;i < spans.size();i+=3){

                Element element = spans.get(i);
                String numText = element.ownText().replace((char) 12288,' ').trim();
                String nameText = element.nextElementSibling().ownText().replace((char) 12288,' ').trim();
                if("市辖区".equals(nameText) || "县".equals(nameText))
                    continue;

                linkedMap.put(Integer.valueOf(numText),nameText);
            }

            // 读取java文件
            bufr = new BufferedReader(new FileReader(filePath));
            StringBuilder newBuilder = new StringBuilder();
            boolean startMark = false;

            String line = "";
            while ((line = bufr.readLine()) != null){

                if(startMark){
                    newBuilder.append("{");
                    for(Map.Entry<Integer,String> me : linkedMap.entrySet()){
                        Integer key = me.getKey();
                        String value = "\"" +  me.getValue() + "\"";
                        newBuilder.append("this.regionMap.put(" + key +"," + value + ");");
                    }
                    newBuilder.append("}").append("}");
                    break;
                }else {
                    newBuilder.append(line);
                }
                if("private Region()".equals(line.trim())){
                    startMark = true;
                }

            }

            // 写入文件
            writer = new BufferedWriter(new FileWriter(filePath,false));
            writer.write(newBuilder.toString());


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                if(null != bufr){
                    bufr.close();
                }
                if(null != writer){
                    writer.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }


    /**
     * 使用javassist 生成 class 文件，反编译之后，将代码拷贝进行手工merger
     * @param filePath
     * @throws NotFoundException
     * @throws IOException
     * @throws CannotCompileException
     */
    public static void parse(String filePath) throws NotFoundException, IOException, CannotCompileException {

        ClassPool classPool = ClassPool.getDefault();

        CtClass ctClass = classPool.makeClass("com.yuanheng100.chinaregion.consts.$Region");

        CtConstructor ctConstructor = new CtConstructor(new CtClass[]{}, ctClass);
        CtField ctField = new CtField(classPool.get("java.util.LinkedHashMap"),"regionMap", ctClass);
        ctField.setModifiers(Modifier.PRIVATE);
        ctClass.addField(ctField,CtField.Initializer.byNew(classPool.get("java.util.LinkedHashMap")));

        BufferedReader buf = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gbk"));

        StringBuilder sb = new StringBuilder("{");
        String line = "";
        while ((line = buf.readLine()) != null){
            String number = line.substring(0, 7).trim();
            String word = line.substring(7).replace((char) 12288,' ').trim();
            char c = word.charAt(0);//12288
            String var1 = "\"" +  new String(word.getBytes("utf-8"),"utf-8").trim() + "\"" ;
            if(word.equals("市辖区") || word.equals("县"))
                continue;
            var1 = var1.replace((char) 12288,' ').trim();
            sb.append("regionMap.put(java.lang.Integer.valueOf(" + number + ")," + var1 + ");");
        }
        sb.append("}");
        ctConstructor.setBody(sb.toString());
        ctConstructor.setModifiers(Modifier.PRIVATE);
        ctClass.addConstructor(ctConstructor);

        ctClass.writeFile();
    }

    public static void main(String[] args) throws IOException, CannotCompileException, NotFoundException {
//        parse("C:\\20160809.txt");
        parse("http://www.stats.gov.cn/tjsj/tjbz/xzqhdm/201608/t20160809_1386477.html","E:\\Develop\\yuanheng\\china-region\\src\\main\\java\\com\\yuanheng100\\chinaregion\\consts\\Region.java");
    }

}
